package com.huoyun.order.action;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;

import com.huoyun.base.action.BaseAction;
import com.huoyun.base.bean.Page;
import com.huoyun.base.bean.Result;
import com.huoyun.car.model.BidCarInfoModel;
import com.huoyun.car.model.SelectedCarsModel;
import com.huoyun.car.service.CarPubInfoService;
import com.huoyun.cargo.service.CargoService;
import com.huoyun.order.bean.Order;
import com.huoyun.order.bean.OrderLog;
import com.huoyun.order.service.OrderLogService;
import com.huoyun.order.service.OrderService;
import com.huoyun.order.service.evt.QueryOrderListEvt;
import com.huoyun.order.service.evt.UpdateOrderStatusEvt;
import com.huoyun.user.bean.Role;
import com.huoyun.user.bean.User;

public class OrderAction extends BaseAction {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private OrderService orderService;

	private OrderLogService orderLogService;
	
	private CarPubInfoService carPubInfoService;
	
	private CargoService cargoService;

	private Order order;

	private long orderId;

	private Page orderPage;

	private Result result;

	/**
	 * 查询订单：状态
	 */
	private String status;

	/**
	 * 查询订单：添加时间
	 */
	private Date addTime;

	private List<Order> orderList;

	private List<OrderLog> orderLogList;
	
	/**
	 * 货物id
	 */
	private long goodsId;
	
	/**
	 * 支付方式, 1:线上支付；2: 货到付款
	 */
	private String payType;
	
	/**
	 * 订单涉及的车辆id集合,用“,”分开
	 */
	private String selectedCarIds;
	
	/**
	 * 订单的拼车方案
	 */
	private SelectedCarsModel selectedCars;

	public String queryAll() {
		try {
			QueryOrderListEvt queryOrderListEvt = new QueryOrderListEvt();

			queryOrderListEvt.setAddTime(addTime);
			queryOrderListEvt.setStatus(status);
			queryOrderListEvt.setPageCount(PAGE_COUNT);
			queryOrderListEvt.setPageNo(pageNo);

			Set<GrantedAuthority> authoritys = (Set<GrantedAuthority>) getLoginUser().getAuthorities();
			// 根据当前登录用户的用户类型设置查询订单的参数
			if (authoritys.contains(new GrantedAuthorityImpl(Role.ROLE_USER))) {
				queryOrderListEvt.setCargosOwnerId(getLoginUser().getId());
			} else if (authoritys.contains(new GrantedAuthorityImpl(Role.ROLE_DRIVER))) {
				queryOrderListEvt.setCarOwnerId(getLoginUser().getId());
			}

			orderPage = orderService.queryList(queryOrderListEvt);
		} catch (Exception e) {
			e.fillInStackTrace();
		}
		return SUCCESS;
	}
	
	public String orderList()
	{
		try {
			QueryOrderListEvt queryOrderListEvt = new QueryOrderListEvt();

			queryOrderListEvt.setAddTime(addTime);
			queryOrderListEvt.setStatus(status);
			queryOrderListEvt.setPageCount(PAGE_COUNT);
			queryOrderListEvt.setPageNo(pageNo);

			Set<GrantedAuthority> authoritys = (Set<GrantedAuthority>) getLoginUser().getAuthorities();
			// 根据当前登录用户的用户类型设置查询订单的参数
			if (authoritys.contains(new GrantedAuthorityImpl(Role.ROLE_USER))) {
				queryOrderListEvt.setCargosOwnerId(getLoginUser().getId());
			} else if (authoritys.contains(new GrantedAuthorityImpl(Role.ROLE_DRIVER))) {
				queryOrderListEvt.setCarOwnerId(getLoginUser().getId());
			}

			orderPage = orderService.queryList(queryOrderListEvt);
		} catch (Exception e) {
			e.fillInStackTrace();
		}
		return SUCCESS;
	}

	/**
	 * 生成订单
	 * 
	 * @author 刘晓宁
	 */
	public String addOrder() 
	{
		try
		{
			//所有应标车辆id集合
			String[] carIds = initSelectedCarIds(selectedCarIds);
			
			orderService.addOrder(goodsId, carIds, getLoginUser(),payType);
		}
		catch (Exception e) 
		{
			// TODO: handle exception
			return ERROR;
		}
		return SUCCESS;
	}
	
	public String viewOrder() {
		try {
			order = orderService.getOrderById(orderId);

			long userId = getLoginUser().getId();

			if (userId != order.getCargosOwnerId() && userId != order.getCarOwnerId()) {
				this.setResultMsg("您没有权限查看该订单详情!");
				return ERROR;
			}

			orderLogList = orderLogService.queryList(orderId);
		} catch (Exception e) {
			// TODO: handle exception
		}
		return SUCCESS;
	}
	
	public String orderConfirm()
	{
		String[] carIds = initSelectedCarIds(selectedCarIds);
		
		List<BidCarInfoModel> bidCarList = carPubInfoService.queryBidCars(goodsId, carIds);
		
		//订单总价格
		BigDecimal price = new BigDecimal("0");
		
		if(bidCarList != null && bidCarList.size() > 0)
		{
			for(BidCarInfoModel bidCarInfo : bidCarList)
			{
				BigDecimal bidCarPrice = new BigDecimal(bidCarInfo.getBidInfoPrice());
				price = price.add(bidCarPrice);
			}
		}
		
		selectedCars = new SelectedCarsModel();
		selectedCars.setPrice(price.toString());
		selectedCars.setBidCarInfoModels(bidCarList);
		selectedCars.setCarIds(selectedCarIds);
		
		return SUCCESS;
	}

	/**
	 * 取消订单
	 * 
	 * @return
	 */
	public String cancelOrder() 
	{
		result = new Result();

		try {
			order = orderService.getOrderById(orderId);

			long userId = getLoginUser().getId();
			
			if(order == null)
			{
				result.setResult(Result.ERROR);
				result.setMessage("订单不存在！");
				return INPUT;
			}
			
			// 判断当前用户是否有取消订单的权限
			if (userId != order.getCarOwnerId() && userId != order.getCargosOwnerId()) 
			{
				result.setResult(Result.ERROR);
				result.setMessage("您没有权限取消该订单！");
				
				return INPUT;
			}
			
			// 取消订单
			UpdateOrderStatusEvt updateOrderStatusEvt = new UpdateOrderStatusEvt();
			updateOrderStatusEvt.setOperateId(getLoginUser().getId());
			updateOrderStatusEvt.setOperateName(getLoginUser().getUsername());
			updateOrderStatusEvt.setOrderId(order.getId());
			updateOrderStatusEvt.setStatus(Order.STATUS_FAILURE);

			orderService.updateOrderStatus(updateOrderStatusEvt);

			result.setResult(Result.SUCCESS);
			result.setMessage("您成功取消了该订单！");
		} catch (Exception e) 
		{
			result.setResult(Result.ERROR);
			result.setMessage("系统忙，请稍后再试！");
			
			return ERROR;
		}

		return SUCCESS;
	}

	public String payOrder() {
		result = new Result();

		try {
			order = orderService.getOrderById(orderId);

			long userId = getLoginUser().getId();
			
			if(order == null)
			{
				result.setResult(Result.ERROR);
				result.setMessage("订单不存在！");
				return INPUT;
			}
			
			// 判断当前用户是否有支付订单的权限
			if (userId != order.getCargosOwnerId()) 
			{
				result.setResult(Result.ERROR);
				result.setMessage("您没有权限支付订单！");
				
				return INPUT;
			}
			
			// 取消订单
			UpdateOrderStatusEvt updateOrderStatusEvt = new UpdateOrderStatusEvt();
			updateOrderStatusEvt.setOperateId(userId);
			updateOrderStatusEvt.setOperateName(getLoginUser().getUsername());
			updateOrderStatusEvt.setOrderId(order.getId());
			updateOrderStatusEvt.setStatus(Order.STATUS_PAYED);

			orderService.updateOrderStatus(updateOrderStatusEvt);

			result.setResult(Result.SUCCESS);
			result.setMessage("您已经完成订单支付！");
		} catch (Exception e) {
			result.setResult(Result.ERROR);
			result.setMessage("系统忙，请稍后再试！");
		}

		return SUCCESS;
	}

	public String completeOrder() {
		result = new Result();

		try {
			order = orderService.getOrderById(orderId);

			long userId = getLoginUser().getId();
			
			if(order == null)
			{
				result.setResult(Result.ERROR);
				result.setMessage("订单不存在！");
				return INPUT;
			}
			
			// 判断当前用户是否有权限
			if (userId != order.getCarOwnerId()) 
			{
				result.setResult(Result.ERROR);
				result.setMessage("您没有完成交易确认！");
				
				return INPUT;
			}
			
			UpdateOrderStatusEvt updateOrderStatusEvt = new UpdateOrderStatusEvt();
			updateOrderStatusEvt.setOperateId(userId);
			updateOrderStatusEvt.setOperateName(getLoginUser().getUsername());
			updateOrderStatusEvt.setOrderId(order.getId());
			updateOrderStatusEvt.setStatus(Order.STATUS_COMPLETED);

			orderService.updateOrderStatus(updateOrderStatusEvt);

			result.setResult(Result.SUCCESS);
			result.setMessage("您已经完成交易确认！");
		} catch (Exception e) {
			result.setResult(Result.ERROR);
			result.setMessage("系统忙，请稍后再试！");
		}

		return SUCCESS;
	}
	
	public String deleteOrder()
	{
		result = new Result();
		
		try
		{
			order = orderService.getOrderById(orderId);
			
			if(order == null)
			{
				result.setResult(Result.ERROR);
				result.setMessage("订单不存在！");
				return INPUT;
			}
			
			if(order.getCargosOwnerId() != getLoginUser().getId())
			{
				result.setResult(Result.ERROR);
				result.setMessage("您没有权利进行此操作！");
				return INPUT;
			}
			
			orderService.deleteOrder(orderId);
			
			result.setResult(Result.SUCCESS);
			result.setMessage("删除成功！");
			
		}
		catch (Exception e) 
		{
			result.setResult(Result.ERROR);
			result.setMessage("操作失败！");
			return ERROR;
		}
		
		return SUCCESS;
	}

	public OrderService getOrderService() {
		return orderService;
	}

	public void setOrderService(OrderService orderService) {
		this.orderService = orderService;
	}

	public Order getOrder() {
		return order;
	}

	public void setOrder(Order order) {
		this.order = order;
	}

	public List<Order> getOrderList() {
		return orderList;
	}

	public void setOrderList(List<Order> orderList) {
		this.orderList = orderList;
	}

	public Page getOrderPage() {
		return orderPage;
	}

	public void setOrderPage(Page orderPage) {
		this.orderPage = orderPage;
	}

	public String getStatus() {
		return status;
	}

	public void setStatus(String status) {
		this.status = status;
	}

	public Date getAddTime() {
		return addTime;
	}

	public void setAddTime(Date addTime) {
		this.addTime = addTime;
	}

	public long getOrderId() {
		return orderId;
	}

	public void setOrderId(long orderId) {
		this.orderId = orderId;
	}

	public Result getResult() {
		return result;
	}

	public void setResult(Result result) {
		this.result = result;
	}

	public OrderLogService getOrderLogService() {
		return orderLogService;
	}

	public void setOrderLogService(OrderLogService orderLogService) {
		this.orderLogService = orderLogService;
	}

	public List<OrderLog> getOrderLogList() {
		return orderLogList;
	}

	public void setOrderLogList(List<OrderLog> orderLogList) {
		this.orderLogList = orderLogList;
	}

	public CarPubInfoService getCarPubInfoService() {
		return carPubInfoService;
	}

	public void setCarPubInfoService(CarPubInfoService carPubInfoService) {
		this.carPubInfoService = carPubInfoService;
	}

	public String getSelectedCarIds() {
		return selectedCarIds;
	}
	
	public void setSelectedCarIds(String selectedCarIds) {
		this.selectedCarIds = selectedCarIds;
	}

	public String[] initSelectedCarIds(String selectedCarIds) {
		if(StringUtils.isNotEmpty(selectedCarIds))
		{
			return selectedCarIds.split(",");
		}

		return null;
	}

	public SelectedCarsModel getSelectedCars() {
		return selectedCars;
	}

	public void setSelectedCars(SelectedCarsModel selectedCars) {
		this.selectedCars = selectedCars;
	}

	public long getGoodsId() {
		return goodsId;
	}

	public void setGoodsId(long goodsId) {
		this.goodsId = goodsId;
	}

	public CargoService getCargoService() {
		return cargoService;
	}

	public void setCargoService(CargoService cargoService) {
		this.cargoService = cargoService;
	}

	public String getPayType() {
		return payType;
	}

	public void setPayType(String payType) {
		this.payType = payType;
	}

}
